package com.briup.cms.service.impl;

import com.briup.cms.config.ConfigProperties;
import com.briup.cms.exception.CustomerException;
import com.briup.cms.service.IUploadLocalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 本地上传服务
 */
@Service
public class DefaultUploadLocalServiceImpl implements IUploadLocalService {


    @Autowired
    private ConfigProperties configProperties;

    @Value("${server.port}")
    private int port;

    @Override
    public List<String> uploadLocalFile(MultipartFile[] files) throws CustomerException {
        List<String> list = new ArrayList<>();
        if(files!=null && files.length>0) {
            for(MultipartFile file:files) {
                list.add(saveFile(file));
            }
        }

        return list;
    }

    private String saveFile(MultipartFile file) {

        // 文件上传路径
        String fileUploadPath = null;
        // 文件访问路径
        String accessPath = "";

        if(!file.isEmpty()) {
            String newFileName = getNewFileName(file);
            fileUploadPath = configProperties.getLocalUploadBastPath()+newFileName;
            accessPath = "http://"+configProperties.getCurrentIp()+":"+port+"/static/"+newFileName;

            File newFile = new File(fileUploadPath);

            if(!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }

            try {
                file.transferTo(newFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return accessPath;

    }

    /**
     * 获取本机的ip地址，如果需要可以使用该方法，自动获得本地ip
     * @return
     */
    private String getCurrentIP() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return address.getHostAddress();
    }

    /**
     * 根据上传文件，获取的文件名字，避免名字重复
     * @param file
     * @return
     */
    private String getNewFileName(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf(".")+1);
        return System.currentTimeMillis()+"."+suffix;
    }

}
